//
//  UpdateUserEmailViewController.swift
//  d11
//
//  Created by rhonin on 2018/10/29.
//  Copyright © 2018年 Tech_001. All rights reserved.
//

import UIKit
import SwiftyJSON
class UpdateUserEmailViewController: UpdateRootViewController {
    
    // 距离父视图顶部间距
    @IBOutlet weak var bottomViewTopConstraint: NSLayoutConstraint!
   
    
    @IBOutlet weak var buttonSingnin: UIButton!
    var timer = TimerHander()
    @IBOutlet weak var labCount: UILabel!
    lazy var loadingView: UIView = {
        
        return UIHelper.initLoadView(self, offsetY: -64)
    }()
    @IBOutlet weak var viewCode: UIView!
    @IBOutlet weak var codeText: UITextField!
    @IBOutlet weak var getCodeBUtton: UIButton!
    @IBOutlet weak var username: UITextField!
    @IBOutlet weak var viewCome: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()

        let layerGradient = CAGradientLayer()
        layerGradient.colors = [
            UIColor.init(red: 1, green: 0.78, blue: 0.45, alpha: 1).cgColor,
            UIColor.init(red: 0.99, green: 0.57, blue: 0.33, alpha: 1).cgColor
        ]
        layerGradient.frame = CGRect(x: 0, y: 0, width: buttonSingnin.frame.width, height: buttonSingnin.frame.height+50)
        buttonSingnin.layer.addSublayer(layerGradient)
        buttonSingnin.layer.cornerRadius = 5
        self.title = "修改邮箱"
        self.getCodeBUtton.clipsToBounds = true
        self.getCodeBUtton.layer.cornerRadius = 6
        self.getCodeBUtton.layer.borderColor = RGBAlpa(255,198,116,1).cgColor
        self.getCodeBUtton.layer.borderWidth = 0.5
        
        self.bottomViewTopConstraint.constant = kNavigationBarHeight
        // 设置导航栏默认返回按钮
        self.leftButtonActionWithImg("icon_default_back")
    }
    
    
    
    @IBAction func updateUserEmail(){
        if !checkEmail(email: username.text!) {
            UIHelper.alertSimpleMessage(about: "", withDescription: "邮箱格式错误", in: self)
            return
        }
        self.loadingView.removeFromSuperview()
        self.view.addSubview(self.loadingView)
        if codeText.text?.count ?? 0 > 0 {
            weak var this = self;
            RequestHelper.post(atPath: "/clientsAPIs/SaveEmail", withData: ["email":username.text!,"code":codeText.text!], withCompletion: { data in
                 let json = JSON(data)
                let code = json["success"].boolValue
                if code {
                    DispatchQueue.main.async {
                      
                        UIHelper.alertSimpleMessage(about: "更改邮箱成功", withDescription: "", in: self)
                        this?.perform(#selector(this?.popcont), with: nil, afterDelay: 0.5)
                        this?.loadingView.removeFromSuperview()
                    }
                }else{
                    DispatchQueue.main.async {
                        UIHelper.alertSimpleMessage(about: "更改失败", withDescription: json["msg"].stringValue, in: self)
                      //  this?.perform(#selector(this?.popcont), with: nil, afterDelay: 0.5)
                        this?.loadingView.removeFromSuperview()
                        
                    }
                }
            },withError: {_ in
                 UIHelper.alertSimpleMessage(about: "服务器异常，\(getErrorString())", withDescription: "", in: self)
            })
        }else{
             UIHelper.alertSimpleMessage(about: "填写邮箱验证码", withDescription: "", in: self)
        }
       
    }
    
   
    @IBAction func getCode(_ sender: Any) {
        if !checkEmail(email: username.text!) {
             UIHelper.alertSimpleMessage(about: "", withDescription: "邮箱格式错误", in: self)
            return
        }
        startTimer()
        RequestHelper.post(atPath: "/clientsAPIs/GetEmailToken", withData: ["email":username.text!], withCompletion: { data in
            let json = JSON(data)
            let code = json["success"].boolValue
            if code  {
                DispatchQueue.main.async {
                     UIHelper.alertSimpleMessage(about: "获取邮箱验证码成功", withDescription: "请查看您的邮箱", in: self)
                
                }
            }else{
                DispatchQueue.main.async {
                    
                    UIHelper.alertSimpleMessage(about: "获取邮箱验证码失败", withDescription:  json["msg"].stringValue, in: self)
                    
                }
            }
        },withError: {_ in
              UIHelper.alertSimpleMessage(about: "服务器异常，\(getErrorString())", withDescription: "", in: self)
        })
    }
    
    func  startTimer(){
        self.timer.startTimer(second: 120) { (count) in
            if count > 0{
                self.labCount.text =  "\(count)s"
                self.getCodeBUtton.isUserInteractionEnabled = false
            }else{
                self.labCount.text = "获取验证码"
                self.getCodeBUtton.isUserInteractionEnabled = true
            }
        }
    }
    
    @objc func popcont()  {
        self.navigationController?.popViewController(animated: true)
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
